package com.efuture.collection;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

/**
 * @ClassNAME HashSetTest
 * @Description HashSet的使用
 * @Author zhaoshanshan
 * @Date 2021/9/7 5:01 下午
 * @Version 1.0
 * HashSet 无序 不可重复
 * 添加自定义对象必须重写equals和hasCode方法
 */
public class HashSetTest {

    public static void main(String[] args) {
        HashSet hashSet = new HashSet();
        //添加元素
        hashSet.add(1);
        hashSet.add("123");
        hashSet.add("12");
        hashSet.add(false);
        //遍历
        Iterator it = hashSet.iterator();
        while (it.hasNext()){
            Object obj = it.next();
            System.out.println(obj);
        }
        System.out.println("==============");
        for (Object obj:hashSet){
            System.out.println(obj);
        }
        //测试重复问题
        hashSet.add("test");
        hashSet.add("test");
        hashSet.add("test");
        System.out.println("==============");
        System.out.println(hashSet.size());//大小为5 三个test只添加进去一个
        System.out.println("==============");
        for (Object obj:hashSet){
            System.out.println(obj);
        }
        System.out.println("==============");
        Set<Student> studentSet = new HashSet<>();
        Student student1 = new Student(11,"shanshan");
        Student student2 = new Student(12,"yifan");
        Student student3 = new Student(11,"tongshuai");
        Student student4 = new Student(12,"yifan");
        studentSet.add(student1);
        studentSet.add(student2);
        studentSet.add(student3);
        studentSet.add(student4);
        System.out.println(studentSet.size());



    }
}
class Student{
    private int no;
    private String name;

    public Student(int no, String name) {
        this.no = no;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return no == student.no && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(no, name);
    }

    @Override
    public String toString() {
        return "Student{" +
                "no=" + no +
                ", name='" + name + '\'' +
                '}';
    }
}